<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
	<title>YUI Library Examples: JSON Utility: JSON with Connection Manager</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    	<link rel="stylesheet" type="text/css" href="/yui/assets/yui.css" >

<style>
/*Supplemental CSS for the YUI distribution*/
#custom-doc { width: 95%; min-width: 950px; }
#pagetitle {background-image: url(/yui/assets/bg_hd.gif);}
#pagetitle h1 {background-image: url(/yui/assets/title_h_bg.gif);}

</style>

<link rel="stylesheet" type="text/css" href="/yui/assets/dpSyntaxHighlighter.css">
<!--Script and CSS includes for YUI dependencies on this page-->
<link rel="stylesheet" type="text/css" href="/yui/build/logger/assets/skins/sam/logger.css" />
<link rel="stylesheet" type="text/css" href="/yui/build/button/assets/skins/sam/button.css" />
<script type="text/javascript" src="/yui/build/yahoo/yahoo-min.js"></script>
<script type="text/javascript" src="/yui/build/event/event-min.js"></script>
<script type="text/javascript" src="/yui/build/dom/dom-min.js"></script>
<script type="text/javascript" src="/yui/build/logger/logger-min.js"></script>
<script type="text/javascript" src="/yui/build/json/json-debug.js"></script>
<script type="text/javascript" src="/yui/build/connection/connection-min.js"></script>
<script type="text/javascript" src="/yui/build/element/element-beta-min.js"></script>
<script type="text/javascript" src="/yui/build/button/button-min.js"></script>


<!--begin custom header content for this example-->

<!--end custom header content for this example-->


</head>
<body id="yahoo-com" class=" yui-skin-sam">
<div id="custom-doc" class="yui-t2">
<div id="hd">
	<div id="ygunav">
		<p><em>
			<a href="http://developer.yahoo.com">Yahoo! Developer Network Home</a> <i> - </i>	
			<a href="http://help.yahoo.com/help/us/ysearch">Help</a>
			</em>
		</p>
		<form action="http://search.yahoo.com/search"><label for="ygsp">YDN Site Search</label> 
		<input name="vs" type="hidden" value="developer.yahoo.com">
		<input name="fr" type="hidden" value="ush-myweb">
		<input id="ygsp" name="va" size="22"> 
		<input type="submit" value="Search" class="ygbt"></form>
	</div>
	<div id="ygma"><a href="/yui/"><img src="/yui/assets/yui.gif"  border="0" width="378" height="28"></a></div>
	<div id="pagetitle"><h1>YUI Library Examples: JSON Utility: JSON with Connection Manager</h1></div>
</div>
<div id="bd">	
	<div id="yui-main">
		<div class="yui-b">
		  <div class="yui-ge">
			  <div class="yui-u first example">
	
	<div class="promo">
	<h1>JSON Utility: JSON with Connection Manager</h1>
	
	<div class="exampleIntro">
	<p>A natural fit for the JSON Utility is working with the <a href="http://developer.yahoo.com/yui/connection/">Connection Manager</a>.  In this example, we'll request JSON data from the server using Connection Manager's <code>asyncRequest</code> and parse the resulting JSON string data for processing.</p>
<p>Click the Get Messages button to send the request to the server.</p>
			
	</div>	
					
	<div class="example-container module ">
			<div class="hd exampleHd">
			<p class="newWindowButton yui-skin-sam"><!--<span id="newWindowLinkx"><span class="first-child">--><a href="json_connect_clean.html" target="_blank">View example in new window.</a><!--</span></span>-->		
		</div>		<div id="example-canvas" class="bd">
	
		
	<!--BEGIN SOURCE CODE FOR EXAMPLE =============================== -->
	
	<div id="demo">
    <input type="button" id="demo_btn" value="Get Messages">

    <div id="demo_msg"></div>
</div>
<script type="text/javascript">
YAHOO.util.Event.on('demo_btn','click',function (e) {
    // Get the div element in which to report messages from the server
    var msg_section = YAHOO.util.Dom.get('demo_msg');
    msg_section.innerHTML = '';

    // Define the callbacks for the asyncRequest
    var callbacks = {

        success : function (o) {
            YAHOO.log("RAW JSON DATA: " + o.responseText);

            // Process the JSON data returned from the server
            var messages = [];
            try {
                messages = YAHOO.lang.JSON.parse(o.responseText);
            }
            catch (x) {
                alert("JSON Parse failed!");
                return;
            }

            YAHOO.log("PARSED DATA: " + YAHOO.lang.dump(messages));

            // The returned data was parsed into an array of objects.
            // Add a P element for each received message
            for (var i = 0, len = messages.length; i < len; ++i) {
                var m = messages[i];
                var p = document.createElement('p');
                var message_text = document.createTextNode(
                        m.animal + ' says "' + m.message + '"');
                p.appendChild(message_text);
                msg_section.appendChild(p);
            }
        },

        failure : function (o) {
            if (!YAHOO.util.Connect.isCallInProgress(o)) {
                alert("Async call failed!");
            }
        },

        timeout : 3000
    }

    // Make the call to the server for JSON data
    YAHOO.util.Connect.asyncRequest('GET',"/xmlProviders/jsonProvider.php", callbacks);
});
</script>
	
	<!--END SOURCE CODE FOR EXAMPLE =============================== -->
	
		
		</div>
		
	
	</div>			
	</div>
		
	<h2 class="first">Include the JSON Utility</h2>
<p>The JSON utility is an extension of <code>YAHOO.lang</code>.  Load the JSON Utility by including these tags:</p>

<textarea name="code" class="HTML" rows="1" cols="60">
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.0/build/yahoo/yahoo-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.0/build/json/json-min.js"></script>

</textarea>

<h2>Use <code>YAHOO.lang.JSON.parse</code> in the success handler</h2>
<p>Pass the XHR <code>responseText</code> to <code>YAHOO.lang.JSON.parse</code> and capture the return value.  Note that the parse method can throw a <code>SyntaxError</code> exception, so be sure to wrap the call in a <code>try/catch</code> block.</p>

<textarea name="code" class="JScript" rows="1" cols="60">
var callbacks = {
    // Successful XHR response handler
    success : function (o) {
        var messages = [];

        // Use the JSON Utility to parse the data returned from the server
        try {
            messages = YAHOO.lang.JSON.parse(o.responseText);
        }
        catch (x) {
            alert("JSON Parse failed!");
            return;
        }

        // The returned data was parsed into an array of objects.
        // Add a P element for each received message
        for (var i = 0, len = messages.length; i < len; ++i) {
            var m = messages[i];
            var p = document.createElement('p');
            var message_text = document.createTextNode(
                    m.animal + ' says "' + m.message + '"');
            p.appendChild(message_text);
            msg_section.appendChild(p);
        }
    },

    ...
};

// Make the call to the server for JSON data
YAHOO.util.Connect.asyncRequest('GET',"assets/jsonConnect.php", callbacks);
</textarea>

<p>The <code>parse</code> method returns the native JavaScript object representation of the string data returned from the <code>asyncRequest</code>.  In this case, the data is an array of object literals in this form:</p>
<textarea name="code" class="JScript" rows="1" cols="60">
[
    { "animal" : "Cat",  "message" : "Meow"  },
    { "animal" : "Dog",  "message" : "Woof"  },
    { "animal" : "Cow",  "message" : "Moo"   },
    { "animal" : "Duck", "message" : "Quack" },
    { "animal" : "Lion", "message" : "Roar"  }
]
</textarea>
				</div>
				<div class="yui-u">
						<div id="loggerModule" class="yui-skin-sam">
						<h3 class="firstContent">YUI Logger Output:</h3>
								<div id="loggerDiv"></div>
						</div>
					
				
					<div id="examples">
						<h3>JSON Utility Examples:</h3>
	
						<div id="exampleToc">
							<ul>
								<li class='selected'><a href='../json/json_connect.html'>JSON with Connection Manager</a></li>							</ul>
						</div>
					</div>
					
					<div id="module">
						<h3>More JSON Utility Resources:</h3>
						<ul>
							<li><a href="http://developer.yahoo.com/yui/json/">User's Guide</a> (external)</li>
						<li><a href="/yui/docs/module_json.html">API Documentation</a></li>
                            
                            
							<li><a href="http://yuiblog.com/assets/pdf/cheatsheets/json.pdf">Cheat Sheet PDF</a> (external)</li></ul>
					</div>
					
	
			  </div>
		</div>
		
		</div>
	</div>


<div class="yui-b" id="tocWrapper">
<!-- TABLE OF CONTENTS -->
<div id="toc">
	
<ul>
<li class="sect first">Yahoo! UI Library</li><li class="item"><a title="The Yahoo! User Interface Library (YUI)" href="http://developer.yahoo.com/yui/">Home (external)</a></li><li class="item"><a title="The Yahoo! User Interface Blog" href="http://yuiblog.com">YUIBlog (external)</a></li><li class="item"><a title="The Yahoo! Group YDN-JavaScript hosts the YUI community forum" href="http://tech.groups.yahoo.com/group/ydn-javascript/">YUI Discussion Forum (external)</a></li><li class="item"><a title="The YUI Library can be downloaded from SourceForge" href="http://sourceforge.net/projects/yui/">YUI on Sourceforge (external)</a></li><li class="item"><a title="Instantly searchable API documentation for the entire YUI library." href="/yui/docs/index.html">API Documentation</a></li><li class="item"><a title="Examples of every YUI utility and control in action" href="/yui/examples/">Functional Examples</a></li><li class="item"><a title="Videos and podcasts from the YUI Team and from the Yahoo! frontend engineering community." href="http://developer.yahoo.com/yui/theater/">YUI Theater (external)</a></li><li class="item"><a title="YUI is free and open, offered under a BSD license." href="http://developer.yahoo.com/yui/license.html">YUI License (external)</a></li><li class="sect">YUI Functional Examples</li><li class="item"><a title="The YUI Animation Utility - Functional Examples" href="/yui/examples/animation/index.html">Animation</a></li><li class="item"><a title="The YUI AutoComplete Control - Functional Examples" href="/yui/examples/autocomplete/index.html">AutoComplete</a></li><li class="item"><a title="The YUI Browser History Manager - Functional Examples" href="/yui/examples/history/index.html">Browser History Manager</a></li><li class="item"><a title="The YUI Button Control - Functional Examples" href="/yui/examples/button/index.html">Button</a></li><li class="item"><a title="The YUI Calendar Control - Functional Examples" href="/yui/examples/calendar/index.html">Calendar</a></li><li class="item"><a title="T
he YUI Charts Control - Functional Examples" href="/yui/examples/charts/index.html">Charts (experimental)</a></li><li class="item"><a title="The YUI Color Picker Control - Functional Examples" href="/yui/examples/colorpicker/index.html">Color Picker</a></li><li class="item"><a title="The YUI Cookie Utility - Functional Examples" href="/yui/examples/cookie/index.html">Cookie (beta)</a></li><li class="item"><a title="The YUI Connection Manager (AJAX) - Functional Examples" href="/yui/examples/connection/index.html">Connection Manager</a></li><li class="item"><a title="The YUI Container Family (Module, Overlay, Tooltip, Panel, Dialog, SimpleDialog) - Functional Examples" href="/yui/examples/container/index.html">Container</a></li><li class="item"><a title="The YUI DataTable Control - Functional Examples" href="/yui/examples/datatable/index.html">DataTable (beta)</a></li><li class="item"><a title="The YUI Dom Collection - Functional Examples" href="/yui/examples/dom/index.html">Dom</a></li><li class="item"><a title="The YUI Drag &amp; Drop Utility - Functional Examples" href="/yui/examples/dragdrop/index.html">Drag &amp; Drop</a></li><li class="item"><a title="The YUI Event Utility - Functional Examples" href="/yui/examples/event/index.html">Event</a></li><li class="item"><a title="The YUI Get Utility - Functional Examples" href="/yui/examples/get/index.html">Get</a></li><li class="item"><a title="The YUI ImageCropper Control - Functional Examples" href="/yui/examples/imagecropper/index.html">ImageCropper (beta)</a></li><li class="item"><a title="The YUI ImageLoader Utility - Functional Examples" href="/yui/examples/imageloader/index.html">ImageLoader</a></li><li class="selected "><a title="The YUI JSON Utility - Functional Examples" href="/yui/examples/json/index.html">JSON</a></li><li class="item"><a title="The YUI Layout Manager - Functional Examples" href="/yui/examples/layout/index.html">Layout Manager (beta)</a></li><li class="item"><a title="The YUI Logger Control - Functional Examples" href="../
../examples/logger/index.html">Logger</a></li><li class="item"><a title="The YUI Menu Control - Functional Examples" href="/yui/examples/menu/index.html">Menu</a></li><li class="item"><a title="The YUI Profiler Utility - Functional Examples" href="/yui/examples/profiler/index.html">Profiler (beta)</a></li><li class="item"><a title="The YUI ProfileViewer Control - Functional Examples" href="/yui/examples/profilerviewer/index.html">ProfilerViewer (beta)</a></li><li class="item"><a title="The YUI Resize Utility - Functional Examples" href="/yui/examples/resize/index.html">Resize (beta)</a></li><li class="item"><a title="The YUI Rich Text Editor - Functional Examples" href="/yui/examples/editor/index.html">Rich Text Editor (beta)</a></li><li class="item"><a title="The YUI Selector Utility - Functional Examples" href="/yui/examples/selector/index.html">Selector (beta)</a></li><li class="item"><a title="The YUI Slider Control - Functional Examples" href="/yui/examples/slider/index.html">Slider</a></li><li class="item"><a title="The YUI TabView Control - Functional Examples" href="/yui/examples/tabview/index.html">TabView</a></li><li class="item"><a title="The YUI TreeView Control - Functional Examples" href="/yui/examples/treeview/index.html">TreeView</a></li><li class="item"><a title="The YUI Uploader Utility - Functional Examples" href="/yui/examples/uploader/index.html">Uploader (experimental)</a></li><li class="item"><a title="The YUI YAHOO Global Object - Functional Examples" href="/yui/examples/yahoo/index.html">YAHOO Global Object</a></li><li class="item"><a title="The YUI Loader Utility - Functional Examples" href="/yui/examples/yuiloader/index.html">YUI Loader (beta)</a></li><li class="item"><a title="The YUI Test Utility - Functional Examples" href="/yui/examples/yuitest/index.html">YUI Test</a></li><li class="item"><a title="YUI Reset CSS - Functional Examples" href="/yui/examples/reset/index.html">Reset CSS</a></li><li class="item"><a title="YUI Base CSS - Functional Examples" href="/yui/exam
ples/base/index.html">Base CSS</a></li><li class="item"><a title="YUI Fonts CSS - Functional Examples" href="/yui/examples/fonts/index.html">Fonts CSS</a></li><li class="item"><a title="YUI Grids CSS - Functional Examples" href="/yui/examples/grids/index.html">Grids CSS</a></li><li class="sect">YUI Articles on the YUI Website</li><li class="item"><a title="Answers to Frequently Asked Questions about the YUI Library" href="http://developer.yahoo.com/yui/articles/faq/">YUI FAQ (external)</a></li><li class="item"><a title="Yahoo!'s philosophy of Graded Browser Support" href="http://developer.yahoo.com/yui/articles/gbs/">Graded Browser Support (external)</a></li><li class="item"><a title="Reporting Bugs and Making Feature Requests for YUI Components" href="http://developer.yahoo.com/yui/articles/reportingbugs/">Bug Reports/Feature Requests (external)</a></li><li class="item"><a title="Serve YUI source files from Yahoo! -- free, fast, and simple" href="http://developer.yahoo.com/yui/articles/hosting/">Serving YUI Files from Yahoo! (external)</a></li><li class="item"><a title="Best practices for working with web services while protecting user privacy" href="http://developer.yahoo.com/security/">Security Best Practices (external)</a></li></ul>
</div>
</div>
	</div><!--closes bd-->

	<div id="ft">
        <p class="first">Copyright &copy; 2008 Yahoo! Inc. All rights reserved.</p>
        <p><a href="http://privacy.yahoo.com/privacy/us/devel/index.html">Privacy Policy</a> - 
            <a href="http://docs.yahoo.com/info/terms/">Terms of Service</a> - 
            <a href="http://docs.yahoo.com/info/copyright/copyright.html">Copyright Policy</a> - 
            <a href="http://careers.yahoo.com/">Job Openings</a></p>
	</div>
</div>
<script src="/yui/assets/dpSyntaxHighlighter.js"></script>
<script language="javascript"> 
dp.SyntaxHighlighter.HighlightAll('code'); 
</script>

<script src='/yui/assets/YUIexamples.js'></script>


</body>
</html>
